<template>
  <div>
    <a-modal :width="670" title="添加员工" :visible="show" @cancel="cancel" @ok="ok">
      <div class="employee-selector-wrapper">
        <div class="employee-selector-block">
          <a-input-search placeholder="搜索员工" style="width: 100%" @search="searchPeople" />
          <!-- 树形选择 -->
          <div class="employee-selector">
            <custom-tree :tree-data.sync="treeData" :is-radio="isRadio" @change="onChange" />
          </div>
        </div>
        <div class="employee-selector-block">
          <div class="employee-selector-title">已经选择的员工({{ selectedListTemp.length }})</div>
          <div v-if="isRadio !== true" class="employee-selector">
            <div v-for="(item, i) in selectedListTemp" :key="i" class="employee-selector-item">
              <div>
                <a-icon type="user" style="margin-right: 6px" />
                {{ item.name }}
              </div>
              <a-icon type="close" @click="deleteItem(item)" />
            </div>
          </div>
          <div v-if="isRadio === true" class="employee-selector">
            <div v-for="(item, i) in selectedListTemp" :key="i" class="employee-selector-item">
              <div>
                <a-icon type="user" style="margin-right: 6px" />
                {{ item.name }}
              </div>
              <a-icon type="close" @click="deleteItem(item)" />
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { getDepEmpInfo } from "@/api/company/contract";
export default {
  components: { customTree: () => import("./memberTree") },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    number: {
      type: Number,
      default: 0
    },
    defaultSelectedKeys: {
      type: Array,
      default: () => []
    },
    isRadio: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      treeData: [],
      selectedDepartmentList: [],
      selectedEmployeeList: [],
      unSelectedEmployeeList: [],
      selectedListTemp: [],
      selectedKeysBeforeSearch: []
    };
  },
  watch: {
    show(val) {
      if (val) {
        if (this.defaultSelectedKeys.length !== this.selectedListTemp.length) {
          this.getSelectDepTree();
        }
      }
    }
  },
  mounted() {
    this.getSelectDepTree();
  },
  methods: {
    onChange(item) {
      this.ergodic(item);
    },
    ergodicInit(isSearch) {
      this.selectedListTemp = [];
      this.unSelectedEmployeeList = [];
      this.selectedEmployeeList = [].concat(this.defaultSelectedKeys, isSearch ? this.selectedKeysBeforeSearch : []);
      this.ergodicEmployeeSelected(this.treeData);
      this.ergodicEmployeeList(this.treeData);
      this.ergodicList(this.treeData);
    },
    ergodic(item) {
      if (!item.isDept || !this.isRadio) {
        this.selectedListTemp = [];
      }
      this.unSelectedEmployeeList = [];
      if (item.isDept) {
        if (this.isRadio) {
          item.isSelected = false;
          return;
        }
        this.ergodicDepartmentSelected(this.treeData, item, item.isSelected);
      } else {
        if (!item.isSelected) {
          this.unSelectedEmployeeList.push(item.id);
        } else {
          if (this.isRadio) {
            this.selectedEmployeeList = [item.id];
          }
        }
      }
      if (!this.isRadio) {
        this.selectedEmployeeList = [];
      }
      this.ergodicEmployeeSelected(this.treeData);
      this.ergodicEmployeeList(this.treeData);
      this.ergodicList(this.treeData);
    },
    ergodicDepartmentSelected(data, obj, selected) {
      if (obj.isDept) {
        data
          .filter((item) => item.isDept)
          .map((item) => {
            if (item.id === obj.id) {
              if (item.hasChild) {
                this.ergodicSelectAll(item.childList, selected);
              }
            } else {
              if (item.hasChild) {
                this.ergodicDepartmentSelected(item.childList, obj, selected);
              }
            }
          });
      }
    },
    ergodicSelectAll(data, selected) {
      data.map((item) => {
        item.isSelected = selected;
        if (item.hasChild) {
          this.ergodicSelectAll(item.childList, selected);
        }
        if (!item.isDept && !selected && !this.unSelectedEmployeeList.includes(item.id)) {
          this.unSelectedEmployeeList.push(item.id);
        }
      });
    },
    ergodicEmployeeSelected(data) {
      data.map((item) => {
        if (item.isDept) {
          if (item.hasChild) {
            this.ergodicEmployeeSelected(item.childList);
          }
        } else {
          if (item.isSelected && !this.isRadio) {
            if (!this.selectedEmployeeList.includes(item.id)) {
              this.selectedEmployeeList.push(item.id);
            }
          }
        }
      });
    },
    ergodicEmployeeList(data) {
      data.map((item) => {
        if (item.isDept) {
          if (item.hasChild) {
            this.ergodicEmployeeList(item.childList);
          }
        } else {
          if (this.selectedEmployeeList.includes(item.id) && !this.unSelectedEmployeeList.includes(item.id)) {
            if (this.selectedListTemp.findIndex((it) => it.id === item.id) === -1) {
              if (this.isRadio) {
                this.selectedListTemp = [];
                this.selectedListTemp.push(item);
              } else if (!this.isRadio) {
                this.selectedListTemp.push(item);
              }
            }
            item.isSelected = true;
          } else {
            item.isSelected = false;
          }
        }
      });
    },
    ergodicList(data, parent) {
      const list = data.filter((item) => item.hasChild);
      if (list.length > 0) {
        for (let i = 0; i < list.length; i++) {
          this.ergodicList(list[i].childList, list[i]);
        }
        if (parent) {
          parent.isSelected = data.length === data.filter((item) => item.isSelected).length;
        }
      } else {
        if (parent) {
          parent.isSelected = data.length === data.filter((item) => item.isSelected).length;
        }
      }
    },
    // 获取部门树
    getSelectDepTree(query) {
      const params = {
        onlyCurrentDep: true,
        onlyUser: true
      };
      if (query) {
        params["empName"] = query;
      }
      getDepEmpInfo(this.$store.state.hr.companyId, params)
        .then((res) => {
          this.treeData = this.formatCompanyData(res.data);
          this.ergodicInit(true);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    formatCompanyData(company) {
      let childList = [];
      if (company.depChildList && company.depChildList.length > 0) {
        childList = childList.concat(this.toTree(company.depChildList));
      }
      if (company.empDirectList && company.empDirectList.length > 0) {
        childList = childList.concat(this.formatEmployeeData(company.empDirectList));
      }
      if (company.noDepEmpList && company.noDepEmpList.length > 0) {
        childList = childList.concat(this.formatEmployeeData(company.noDepEmpList));
      }
      return [
        {
          id: company.id,
          name: company.name,
          isDept: true,
          isSelected: false,
          hasChild: childList.length > 0,
          childList: childList
        }
      ];
    },
    formatEmployeeData(employee) {
      return employee.map((item) => ({
        id: item.id,
        name: item.name,
        phone: item.phone,
        idCard: item.idCard,
        depName: item.depName,
        positionName: item.positionName,
        isDept: false,
        isSelected: false,
        hasChild: false
      }));
    },
    toTree(data) {
      const data_new = data.map((item) => {
        let arr = [];
        if (item.depChildList && item.depChildList.length > 0) {
          arr = arr.concat(this.toTree(item.depChildList));
        }
        if (item.empDirectList && item.empDirectList.length > 0) {
          arr = arr.concat(this.formatEmployeeData(item.empDirectList));
        }
        if (arr.length > 0) {
          return {
            id: item.id,
            name: item.name,
            isDept: true,
            isSelected: false,
            hasChild: arr.length > 0,
            childList: arr
          };
        } else {
          return null;
        }
      });
      return data_new.filter((item) => !!item);
    },
    searchPeople(query) {
      this.selectedKeysBeforeSearch = this.selectedListTemp.map((item) => item.id);
      this.getSelectDepTree(query);
    },
    deleteItem(item) {
      item.isSelected = false;
      this.ergodic(item);
    },
    ok() {
      this.$emit("update:selectedList", this.selectedListTemp);
      this.$emit(
        "update:selectThree",
        this.selectedListTemp
          .slice(0, 3)
          .map((item) => item.name)
          .join(",")
      );
      this.$emit("update:show", false);
      this.$emit("change", this.selectedListTemp);
    },
    cancel() {
      this.$emit("update:show", false);
    }
  }
};
</script>
